//
//  NewFeatureController.swift
//  Sina
//
//  Created by maling  on 15/11/7.
//  Copyright © 2015年 maling . All rights reserved.
//

import UIKit
//可重用cell标示
private let WBNewFeatureViewCellId = "WBNewFeatureViewCellId"
//新特性图像数量
private let WBNewFetureImageCount = 4

class NewFeatureController: UICollectionViewController {

    // 懒加载属性 必须要在控制器实例化之后才被创建
    // MARK: 构造函数
    init() {
       
     let layout = UICollectionViewFlowLayout()
        //设置cell 的样式
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .Horizontal
        //构造函数完成之后内部属性才能被创建
        
      super.init(collectionViewLayout: layout)
    
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
        
    }

    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // iOS 7.0 开始，就推荐要隐藏状态栏，可以每个控制器分别设置，默认是 NO
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()

        
        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: WBNewFeatureViewCellId)


    }



    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return WBNewFetureImageCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WBNewFeatureViewCellId, forIndexPath: indexPath) as! NewFeatureCell
    
       
        cell.imageIndex = indexPath.item
        return cell
    }

    /// ScrollView 停止滚动方法 停止滚动后才让动画
   override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        // 在最后一页才调用动画方法
        // 根据 contentOffset 计算页数
       let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
    
         //判断是否是最后一页
    if page != WBNewFetureImageCount - 1 {
       return
    }
    //cell 播放动画
    let cell = collectionView?.cellForItemAtIndexPath(NSIndexPath(forItem: page, inSection: 0)) as! NewFeatureCell
//                                        NSIndexPath(forItem: <#T##Int#>, inSection: <#T##Int#>)
    //显示动画
    cell.showButtonAnim()
    }
  
}

/// 自定义cell
//MARK: - 新特性cell
 class NewFeatureCell: UICollectionViewCell {


//  /// 图片属性
    private var imageIndex: Int = 0 {
    
        didSet {
            iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
        
            //隐藏按钮
            startButton.hidden = true
        }
        
    }
    
    //点击按钮函数
    @objc private func clickButton() {
    
        print("开始体验")
        
        NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: nil)
    }
    
    /// 显示按钮 动画效果
    private func showButtonAnim() {
    
        //第四个执行动画 不隐藏按钮
        startButton.hidden = false
        //刚开始按钮
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        startButton.userInteractionEnabled = false
        
        UIView.animateWithDuration(1.6,  // 动画时长
            delay: 0,                    // 延时时间
            usingSpringWithDamping: 0.6, // 弹力系数 0~1 越小越弹
            initialSpringVelocity: 10,   // 初始速度 模拟重力加速度
            options: [],                 // 动画选项
            animations: { () -> Void in
            
            self.startButton.transform = CGAffineTransformIdentity
            
            }) { (_) -> Void in
                
            self.startButton.userInteractionEnabled = true
        }
    
    
    }

    
    
    override init(frame: CGRect) {
    
        super.init(frame: frame)
        print("创建cell")

        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//   //MARK: - 设置添加到View上面
    private func setupUI() {
    
        //1.添加控件
        addSubview(iconView)
        addSubview(startButton)
        // 隐藏按钮（目的是不让前3个cell 显示cell）
//        startButton.hidden = true
        
        
        //2.指定空间位置
        iconView.frame = bounds
       
        startButton.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX)
            make.bottom.equalTo(self.snp_bottom).multipliedBy(0.7)
        }
        
        //3.按钮的监听方法
        startButton.addTarget(self, action: "clickButton", forControlEvents: .TouchUpInside)
        
        
    }
    
    
    
    // 懒加载图片属性
    private lazy var iconView: UIImageView = UIImageView()
    //懒加载体验按钮属性
    private lazy var startButton: UIButton = UIButton(title: "开始体验", color: UIColor.whiteColor(), imageName:"new_feature_finish_button")
    

}



